<script setup lang="ts">
import type { PropType } from 'vue'
import type { IFormItem } from '@/types/index'
import { cloneDeep } from 'lodash'
import { onBeforeUnmount, onMounted, ref } from 'vue'

interface IPopoverData {
  prop: string
}
const props = defineProps({
  item: {
    type: Object as PropType<IFormItem>,
    required: true,
  },
  popoverVisible: Boolean,
  popoverData: Array as PropType<IPopoverData[]>,
  inputRef: Object,
})

// const instance = getCurrentInstance()
// const emit = instance?.proxy?.$emit
const emit = defineEmits(['update:popoverData'])
const popoverRef = ref()
function handleDelete(index: number) {
  // props.popoverData?.splice(index, 1)
  const data = cloneDeep(props.popoverData)
  data?.splice(index, 1)
  emit('update:popoverData', data)
}

function handleCheck() {
  // props.item.value = String(props.popoverData?.map(val => val.prop))
}
function handleKeyDown(event: KeyboardEvent) {
  if (event.key === 'Escape') {
    // Esc关闭popover
  }
}
function handleClose() {
}
function setupKeyListener() {
  window.addEventListener('keydown', handleKeyDown)
}
function removeKeyListener() {
  window.removeEventListener('keydown', handleKeyDown)
}
onMounted(() => {
  setupKeyListener()
})
onBeforeUnmount(() => {
  removeKeyListener()
})
</script>

<template>
  <el-popover
    ref="popoverRef" class="item-popover" placement="bottom-end" width="240" :visible="popoverVisible"
    :virtual-ref="inputRef"
  >
    <div class="popover-main">
      <div class="btn-part">
        <el-button size="small" type="danger" icon="CloseBold" circle @click="handleClose()" />
        <el-button size="small" type="primary" icon="Check" circle @click="handleCheck()" />
      </div>
      <div class="table-part">
        <el-table :data="popoverData" style="width: 100%" height="180" empty-text="空数据">
          <el-table-column prop="prop">
            <template #default="scope">
              <el-input v-model="scope.row.prop" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="60">
            <template #default="scope">
              <el-button
                size="small" type="danger" icon="Delete" circle
                @click="handleDelete(scope.$index)"
              />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-popover>
</template>

<style scoped lang='scss'>
.item-popover {
    position: absolute !important;
    top: 100% !important;
    left: 0 !important;
    margin-top: 5px !important;
}

.popover-main {
    width: 100%;
    height: 220PX;
    display: flex;
    flex-direction: column;

    .el-button {
        width: 18px;
        height: 18px;
        border-radius: 50%;
    }

    .btn-part {
        display: flex;
        justify-content: space-between;
        width: 100%;

    }

    .table-part {
        flex-grow: 1;
        overflow: hidden;
    }
}
</style>
